package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;

/**
 * @author acc8226
 */
public class JdbcDemo {

    public static void main(String[] args) {
        String propertiesFileName = Objects.requireNonNull(JdbcDemo.class.getClassLoader().getResource("cn/java/mysql-sample-properties.xml")).getFile();
        JDBCTutorialUtilities myJDBCTutorialUtilities;
        Connection con = null;

        try {
            myJDBCTutorialUtilities = new JDBCTutorialUtilities(propertiesFileName);
        } catch (Exception e) {
            System.err.println("Problem reading properties file " + propertiesFileName);
            e.printStackTrace();
            return;
        }

        try {
            con = myJDBCTutorialUtilities.getConnection();
            query(con);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCTutorialUtilities.closeConnection(con);
        }
    }

    private static void query(Connection con) throws SQLException {
        String query = "SELECT username FROM users";
        try (Statement stmt = con.createStatement()) {
            ResultSet rs = stmt.executeQuery(query);
            if (rs.next()) {
                System.out.println("username = " + rs.getString(1));
            }
        }
    }
}
